import React, { useRef, forwardRef } from 'react';
import { truncate } from 'loadsh';
import PropTypes from 'prop-types';
import './input.css';
function Input_(props, ref) {
  const {
    style,
    placeholder,
    value,
    prefix,
    suffix,
    suffixClick,
    prefixClick,
    disabled,
    onFocus,
    onChange,
    onClick,
    onBlur,
    className,
  } = props;
  // suffixClick, prefixClick  前缀和后缀的点击事件

  const prefixRef = useRef(null);
  const suffixRef = useRef(null);

  const prefixBoder = (n) => {
    let color = n === 'focus' ? '#2ca63b' : '#d9d9d9';
    if (prefixRef.current) {
      prefixRef.current.style.borderColor = color;
    }
    if (suffixRef.current) {
      suffixRef.current.style.borderColor = color;
    }
  };

  // console.log('value ===> ', )

  return (
    <div
      className={`inputDom_box ${disabled && 'input_disable'} ${className}`}
      style={style}
    >
      {prefix && (
        <span
          ref={prefixRef}
          onClick={() => {
            if (prefixClick) prefixClick(prefixRef);
          }}
          className="prefix"
        >
          {prefix}
        </span>
      )}
      <input
        type="text"
        className={`Input ${prefix ? 'havePrefix' : 'noPrefix'} ${
          suffix ? 'havaSuffix' : 'noSuffix'
        }`}
        // 如果传递了value 就让他受控
        value={value}
        disabled={disabled}
        ref={ref}
        onChange={(e) => onChange && onChange(e.target.value)}
        onClick={() => onClick && onClick()}
        onFocus={() => {
          prefixBoder('focus');
          onFocus && onFocus();
        }}
        onBlur={() => {
          prefixBoder('blue');
          onBlur && onBlur();
        }}
        placeholder={placeholder}
      />
      {suffix && (
        <span
          ref={suffixRef}
          onClick={() => {
            if (suffixClick) suffixClick(suffixRef);
          }}
          className={`suffix`}
        >
          {suffix}
        </span>
      )}
    </div>
  );
}

const Input = forwardRef(Input_);

// 类型检查
Input.propTypes = {
  style: PropTypes.object,
  placeholder: PropTypes.string,
  value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
  prefix: PropTypes.element,
  suffix: PropTypes.element,
  disabled: PropTypes.bool,
  onChange: PropTypes.func,
  onFocus: PropTypes.func,
  onClick: PropTypes.func,
  onBlur: PropTypes.func,
  className: PropTypes.oneOfType([PropTypes.string]),
};

export default Input;
